"""


	PAL Tools


"""




import sys
import os, stat, time


class Log:
    def __init__( self, fileName, out=False, err=False ):
        self.replaced = [None,None]
        self.fileName = fileName
        w = open( self.fileName, 'w' )
        w.write( "OPENING LOG: "+self.fileName+"\n\n" )
        w.close()
        self.replace_sys(out,err)

    def replace_sys(self, out=False, err=False ):
        if out:
          self.replaced[0] = sys.stdout
          sys.stdout = self
        if err:
          self.replaced[1] = sys.stderr
          sys.stderr = self

    def restore_sys(self, out=True, err=True ):
        if out and self.replaced[0] is not None:
          sys.stdout = self.replaced[0]
        if err and self.replaced[1] is not None:
          sys.stderr = self.replaced[1]
  
    def write(self, str ):
        w = open( self.fileName, 'a' )
        w.write( str )
        w.close()
        #self.p(str)
    
    def p(self, *args ):
        for s in args:
          self.replaced[0].write(">>>"+s+"\n")


class LogWatcher:
    def __init__( self, filename ):
        self.filename = filename
        self.mtime = None
        self.len = 0
        
    def start(self):
        while True:
            mtime = os.stat(self.filename)[8]
            if mtime != self.mtime:
                print '##### TOUCHED #####'
                r = open( self.filename, 'r' )
                r.seek(self.len)
                print r.read()
                self.len = r.tell()-1
                r.close()
                self.mtime = mtime
            time.sleep(1)
        
def _AddMyToPath():
    import pal_config
    MYPATH = os.path.join( pal_config.PALPATH, 'MY' )
    if MYPATH not in sys.path:
        sys.path.insert(0,MYPATH)

def MakeDoc( moduleName, path, skipList=[], moduleDir=None, dotInLink=False, recurse=True ):
    '''
    Create the doc of a module and its sub modules.
    skipList is a list of module names to skip.
    
    If moduleDir is None, the first part of moduleName is used.
    If dotInLink is False, generated files will be named by the
    last part of moduleName.
    
    '''
    import os.path
    _AddMyToPath()
    
    # check given path
    if not os.path.isdir( path ):
        raise Exception( "Path for doc doesn't exists !!!" )
    
    # create the sub folder if needed
    if moduleDir is None:
        moduleDir = os.path.join( path, moduleName.split('.')[-1] )
    path = os.path.join( path, moduleDir )
    if not os.path.isdir( path ):
        os.mkdir( path )
    
    # compute the file name
    if not dotInLink:
        fileName = os.path.join( path, moduleName.split('.')[-1] )+'.html'
    else:
        fileName = os.path.join( path, moduleName )+'.html'
        
    # go
    import my_pydoc
    print 'Creating doc for', moduleName, 'in', fileName
    object = my_pydoc.locate(moduleName)
    page = my_pydoc.html.page(
        my_pydoc.describe(object),
        my_pydoc.html.document(object, moduleName)
    )
    file = open(fileName, 'w')
    file.write(page)
    file.close()
    print 'Wrote doc to', fileName
    skipList.append( moduleName )
    
    if not recurse:
        return
        
    import my_inspect
    subs = my_inspect.getmembers( object, my_inspect.ismodule )
    for subName, obj in subs:
        print subName, '?'
        if subName in skipList:
            print "------ Skipping Sub Module", moduleName+'.'+subName
            continue
        MakeDoc( moduleName+'.'+subName, path, skipList, moduleDir=moduleDir )

    objDir=None
    try:
        objDir = os.path.dirname(object.__file__)
    except:
        pass
    if objDir is not None:
        files = os.listdir(objDir)
        for f in files:
            subName, ext = os.path.splitext(f)
            subName = subName.split('.')[-1]
            print ">>SUBNAME:", subName
            if subName in skipList:
                print "------ Skipping Sub File ", subName
                continue
            MakeDoc(
                moduleName+'.'+subName, path, [],
                moduleDir=moduleDir, dotInLink=True, recurse=False
            )
